import { FormGroup, FormBuilder, Validators } from '@angular/forms';

export class FormComponent {
  form: FormGroup; //表单
  submitted = false; //是否提交
  fb: FormBuilder = new FormBuilder(); //ng Form

  /**
   * 构建表单  
   * 
   * @param {*} controls 
   * @memberof FormComponent
   */
  buildForm(controls: any) {
    this.form = this.fb.group(controls);
  }

  /**
   * 重置表单
   * 
   * @memberof FormComponent
   */
  resetForm() {
    this.form.reset();
    this.submitted = false;
  }


  /**
   * 设置表单值
   * 
   * @param {string} control 
   * @param {string} value 
   * @memberof FormComponent
   */
  setFormControlValue(control: string, value: any) {
    this.getFormControl(control).setValue(value);
  }

  /**
   * 获取表单值
   * 
   * @param {string} control 
   * @memberof FormComponent
   */
  getFormControleValue(control: string) {
    return this.getFormControl(control).value;
  }

  /**
   * 提交表单
   * 
   * @memberof FormComponent 
   */
  submitForm(doSubmit: Function) {
    for (const i in this.form.controls) {
      this.form.controls[i].markAsDirty();
    }
    if (this.form.valid) {
      this.submitted = true;
      doSubmit();
    }
  }

  /** 
   * 获取表单control对象
   * 
   * @param {any} name 
   * @returns 
   * @memberof ChangePwdComponent
   */
  getFormControl(name: string): any {
    return this.form.controls[name];
  }

  /**
   * 表单错误
   * 
   * @param {string} name 
   * @param {(string | Array<string>)} errors 
   * @memberof FormComponent
   */
  hasErrors(name: string, errors: string | Array<string>) {
    let control = this.getFormControl(name);
    let error = false;
    // TODO: 多个error处理 ['required','ip'] 
    if (errors && typeof errors === 'string') {
      error = control.hasError(errors);
    }
    return control.dirty && error;
  }
}